package com.marst.first.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.marst.first.bean.Role;
import com.marst.first.bean.RoleMenu;
import com.marst.first.bean.VO.Result;
import com.marst.first.mapper.RoleMapper;
import com.marst.first.mapper.RoleMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    public Result addRole(Role role) {
        if (StringUtils.isEmpty(role.getName())){
            return new Result(1003,"名字不能为空");
        }
        int roleCountByName = roleMapper.getRoleCountByName(role.getName());
        if (roleCountByName > 0){
            return new Result(1005,"名字不能重复");
        }
        role.setCreateTime(new Date());
        roleMapper.insert(role);

        log.info("菜单列表: {}", JSONObject.toJSONString(role.getMenuList()));

        for (int i = 0; i < role.getMenuList().length; i++) {
            //从菜单列表中逐个取出 菜单id
            int menuId = role.getMenuList()[i];

            //初始化角色菜单关联关系实例
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getId());
            roleMenu.setMenuId(menuId);
            roleMenu.setCreateTime(new Date());
            //逐个新增关联关系
            roleMenuMapper.insert(roleMenu);
        }

        log.info("insert role success ....");

        return Result.ok();
    }

    public Result getAllRole(int pageSize, int pageNum, String name) {


        pageSize = pageSize==0 ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roles = roleMapper.getRoleList(name);
        return Result.ok(new PageInfo<>(roles));
    }

    public Result getRoleById(int id) {
        Role role = roleMapper.selectById(id);
        return Result.ok(role);
    }

    public Result deleteRoleById(int id) {
        roleMapper.deleteById(id);
        return Result.ok();
    }

    public Result deleteUserOnLogic(int id) {
        roleMapper.deleteRoleOnLogic(id);
        return Result.ok();
    }


    public Result updateRoleById(Role role) {
        roleMapper.updateById(role);
        return Result.ok();
    }
}
